<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use think\Db;

class Menu extends Common
{
    public function index()
    {   
        // 用户权限
        $role = $this->roles_users();
        $db = DB::name('sort');
        $w['status'] = array('eq',1);
        $w['pid'] = array('eq',0);
        $list = $db->where($w)->order('disorder asc,id asc')->select();
        // 一级菜单
        $arr = array();
        foreach ($list as $k => $v) {
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['catname'] = $v['catname'];
            $arr[$k]['path'] = $v['sort_c'];
            if(!empty($role[0]) && !in_array($v['id'],$role)){
                unset($arr[$k]);
            }
            // 二级菜单
            $list2 = $db->where(array('status'=>1,'pid'=>$v['id']))->order('disorder asc,id asc')->select();
            $arr2 = array();
            foreach ($list2 as $k2 => $v2) {
                    $arr2[$k2]['id'] = $v2['id'];
                    $arr2[$k2]['catname'] = $v2['catname'];
                    $arr2[$k2]['path'] = $v2['sort_c'];
                    if(!empty($role[0]) && !in_array($v2['id'],$role)){
                        unset($arr2[$k2]);
                    }
                    // 三级菜单
                    $arr3 = array();
                    $list3 = $db->where(array('status'=>1,'pid'=>$v2['id']))->order('disorder asc,id asc')->select();
                    foreach ($list3 as $k3 => $v3) {
                        $arr3[$k3]['id'] = $v3['id'];
                        $arr3[$k3]['catname'] = $v3['catname'];
                        $arr3[$k3]['path'] = $v3['sort_c'];
                        if(!empty($role[0]) && !in_array($v3['id'],$role)){
                            unset($arr3[$k3]);
                        }
                        // 没有四级菜单
                        // $arr3[$k3]['children'] = array();
                    }
                if($arr3) $arr2[$k2]['children'] = $arr3;
            }
            if($arr2) $arr[$k]['children'] = $arr2;
        }
        $menu['data'] = $arr;
        $menu['meta'] = array('msg'=>'获取菜单列表成功','status'=>200);
        return json_encode($menu);
    }

}